// createAsyncThunk文档: https://redux-toolkit.js.org/api/createAsyncThunk
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import baseApi from '../api/base'

// 异步方式1 (1)
export const loadGoods = createAsyncThunk(
  'dic/fetchGoods',
  (data, thunkAPI) => {
    baseApi.findGoods(data).then(res => {
      console.log('loadGoods thunkAPI:', thunkAPI)
      thunkAPI.dispatch(setGoods(res.result))
    })
  }
)

// 异步方式2 (1)
export const loadGoods2 = createAsyncThunk(
  'dic/fetchGoods2',
  (data, thunkAPI) => {
    return baseApi.findGoods(data).then(res => res.result)
  }
)


export const counterSlice = createSlice({
  name: 'dic',
  initialState: {
    sortList: [
      { label: '食品类', value: '食品类' },
      { label: '服装类', value: '服装类' },
      { label: '鞋帽类', value: '鞋帽类' },
      { label: '日用品类', value: '日用品类' },
      { label: '家具类', value: '家具类' },
      { label: '家用电器类', value: '家用电器类' },
      { label: '纺织品类', value: '纺织品类' },
      { label: '厨具类', value: '厨具类' },
      { label: '五金电料类', value: '五金电料类' },
    ],
    unitList: [
      { label: 'kg', value: 'kg' },
      { label: '瓶', value: '瓶' },
      { label: '个', value: '个' },
      { label: '箱', value: '箱' },
      { label: '包', value: '包' },
    ],
    statusList: [
      { label: '在架中', value: '在架中' },
      { label: '未在架', value: '未在架' },
    ],
    sexList: [
      { label: '男', value: '男' },
      { label: '女', value: '女' },
    ],
    
    goodsData: [],
  },
  reducers: {
    changeVal: (state, action) => {
      console.log('', JSON.parse(JSON.stringify(state)), state, action)
    },
    // 异步方式1 (2)
    setGoods: (state, action) => {
      console.log('setGoods', action)
      state.goodsData = action.payload
    }
  },
  // 异步方式2 (2)
  extraReducers: {
    // 异步函数成功fulfilled时回调(类似的还有pending等待、rejected拒绝，此处只列举成功态) 
    [loadGoods2.fulfilled](state, action) {
      state.goodsData = action.payload
    },
  }

})

export const { changeVal, setGoods } = counterSlice.actions

export default counterSlice.reducer
